<template>
  <div class="relative" ref="selectRef">
    <div @click="toggleOpen">
      <slot name="trigger" />
    </div>
    
    <div
      v-if="isOpen"
      class="absolute top-full left-0 z-50 min-w-full mt-1 bg-popover border rounded-md shadow-lg"
      @click="handleContentClick"
    >
      <slot name="content" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, onUnmounted } from 'vue'

interface SelectProps {
  modelValue?: string
}

const props = defineProps<SelectProps>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const isOpen = ref(false)
const selectRef = ref<HTMLElement>()

const toggleOpen = () => {
  isOpen.value = !isOpen.value
}

const closeSelect = () => {
  isOpen.value = false
}

const handleContentClick = (event: Event) => {
  event.stopPropagation()
}

const handleClickOutside = (event: Event) => {
  if (selectRef.value && !selectRef.value.contains(event.target as Node)) {
    closeSelect()
  }
}

const selectValue = (value: string) => {
  emit('update:modelValue', value)
  closeSelect()
}

// 提供给子组件使用
provide('selectValue', selectValue)
provide('currentValue', props.modelValue)
provide('closeSelect', closeSelect)

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>